package com.aurora.demo.service;

import com.aurora.demo.api.vo.SimilarImageVO;
import com.aurora.demo.entity.Feature;
import com.aurora.demo.repository.FeatureRepository;
import com.aurora.demo.util.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class FeatureService {

    @Autowired
    private FeatureRepository featureRepository;

    public void save(MultipartFile file) {
        String name = file.getOriginalFilename().substring(0, 13);
        try {
            byte[] sourceBytes = file.getBytes();
            String feature = ImageUtil.generateFeature(sourceBytes);
            Feature feature1 = new Feature();
            feature1.setName(name);
            feature1.setFeature(feature);
            featureRepository.save(feature1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public SimilarImageVO getBySimilar(MultipartFile file) {
        String name = file.getOriginalFilename().substring(0, 13);
        List<Feature> featureList = featureRepository.findAll();
        int minFeatureValue = 100;
        List<String> nameList = new ArrayList<>();
        try {
            byte [] bytes = file.getBytes();
            String featureValue = ImageUtil.generateFeature(bytes);
            for(Feature feature : featureList) {
                int difference = ImageUtil.hammingDistance(featureValue, feature.getFeature());
                if(difference < minFeatureValue) {
                    nameList.clear();
                    minFeatureValue = difference;
                    nameList.add(feature.getName());
                } else if(difference == minFeatureValue) {
                    nameList.add(feature.getName());
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        SimilarImageVO similarImageVO = new SimilarImageVO();
        similarImageVO.setDifference(16 - minFeatureValue);
        similarImageVO.setNameList(nameList);
        return similarImageVO;
    }
}
